package cell 
{
	import flash.display.Sprite;
	import flash.events.Event;
	
	/**
	 * ...
	 * @author a.orleansky
	 */
	public class KeyPad extends Sprite 
	{
		public static const KEY_PAD_RELEASED:String = "KEY_PAD_RELEASED";
		
		private var names:Array = new Array("1", "2", "3", "4", "5", "6", "7", "8", "9", "C", "0", "D");
		private var entered_str:String;
		private var limit:Number = 30;
		private var pic_count:Number;
		public var gap:Number = 2;
		
		public function KeyPad(_gap:Number=2) 
		{
			gap = _gap;
			addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		public function init(e:Event=null):void {
			removeEventListener(Event.ADDED_TO_STAGE, init);
			entered_str = "";
			pic_count = 0;
			createKeyPad();
		}
		
		public function set num_limit(num:Number):void {
			limit = num;
		}
		
		public var btns:Array;
		
		public function createKeyPad():void {
			btns = new Array();
			pic_count = names.length;
			for (var ii:Number = 0; ii < names.length; ii++ ) {
				var btn:KeyPadBtn = new KeyPadBtn();
				btn.init(names[ii]);
				btn.addEventListener(KeyPadBtn.KEY_PAD_BTN_CLICK, onPressbBtn);
				btn.addEventListener(KeyPadBtn.KEY_PAD_BTN_LOADED, allPicLoaded);
				btns[ii] = btn;
				addChild(btns[ii]);
			}
		}
		
		private function allPicLoaded(e:Event):void 
		{
			pic_count--;
			if (pic_count == 0) {
				for (var ii:Number = 0; ii < btns.length; ii++ ) {
					var btn:KeyPadBtn = btns[ii];
					btn.x = (btn.width+gap)* (ii % 3);
					btn.y = (btn.height+gap) * (Math.floor(ii / 3));
				}
				
			}
		}
		
		public function clearBuffer():void {
			entered_str = "";
		}
		
		public function get entered_value():String {
			return entered_str;
		}
		public function set rewrite_value(str:String):void {
			entered_str = str;
		}
		
		public function clearEnteredValue():void {
			entered_str = "";
		}
		
		public function onPressbBtn(e:Event):void {
			var btn:KeyPadBtn = (e.target as KeyPadBtn);
			switch(btn.indx) {
				case "C":
					entered_str = "";
					break;
				case "D":
					entered_str = entered_str.slice(0, (entered_str.length-1));
					break;
				default:
					if(entered_str.length < limit)entered_str += btn.indx;
			}
			dispatchEvent(new Event(KEY_PAD_RELEASED,true));
		}
	}

}